package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonDemo {
	public void print() {
		//json字符串-简单对象型
		String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
		//json字符串-数组类型
		String  JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
		//复杂格式json字符串
		String  COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";
				
		
		//示例1.1-json字符串-简单对象型与JSONObject之间的转换
		JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
		System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
		
		//示例1.2-json字符串-数组类型与JSONArray之间的转换
		JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
        //JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON，所以这样也是可以的
		System.out.println("------------");
        //遍历方式1
        int size = jsonArray.size();
        for (int i = 0; i < size; i++){
            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
            System.out.println(jsonObject2.getString("studentName")+":"+jsonObject2.getInteger("studentAge"));
        }

        //遍历方式2
//        for (Object obj : jsonArray) {
//            JSONObject jsonObject = (JSONObject) obj;
//            System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
//        }
        
        System.out.println("------------");
        //示例1.3-复杂json格式字符串与JSONObject之间的转换
        JSONObject jsonObject3 = JSON.parseObject(COMPLEX_JSON_STR);
        //JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);//因为JSONObject继承了JSON，所以这样也是可以的
        
        String teacherName = jsonObject3.getString("teacherName");
        Integer teacherAge = jsonObject3.getInteger("teacherAge");
        JSONObject course = jsonObject3.getJSONObject("course");
        JSONArray students = jsonObject3.getJSONArray("students");
		
        for (Object obj : students) {
            JSONObject jsonObject4 = (JSONObject) obj;
            System.out.println(jsonObject4.getString("studentName")+":"+jsonObject4.getInteger("studentAge"));
        }
	}
}
